package cn.tedu.config;

import cn.tedu.controller.AccessInterceptor;
import cn.tedu.controller.DemoInterceptor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.thymeleaf.spring5.SpringTemplateEngine;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
import org.thymeleaf.templatemode.TemplateMode;
import org.thymeleaf.templateresolver.ClassLoaderTemplateResolver;

@Configuration
@ComponentScan("cn.tedu.controller")
@EnableWebMvc
/*WebMvcConfigurer是SpringMVC提供的配置模板
需要配合@EnableWebMvc注解一起使用*/
public class SpringMvcConfig implements WebMvcConfigurer {
    /* 重写配置模板中的拦截器配置方法*/
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
    /*  创建DemoInterceptor对象,注册到SpringMVC中
        ddPathPatterns()方法到作用是约定拦截到URL
        如下代码:注册一个拦截器,在请求/home/index.do时候执行拦截器到功能*/
//        registry.addInterceptor(new DemoInterceptor()).addPathPatterns("/home/index.do");
        registry.addInterceptor(new AccessInterceptor()).addPathPatterns(
                "/home/*",
                "user/*",
                "/blog/**")
                .excludePathPatterns(
                        "/user/login.do",
                        "/user/handle_login.do",
                        "/user/reg.do");

//        WebMvcConfigurer.super.addInterceptors(registry);
    }

    /*配置视图解析器*/
    @Bean
    public ThymeleafViewResolver viewResolver() {
        ClassLoaderTemplateResolver templateResolver = new ClassLoaderTemplateResolver();
        templateResolver.setPrefix("/static/");
        templateResolver.setSuffix(".html");
        templateResolver.setTemplateMode(TemplateMode.HTML);
        templateResolver.setCharacterEncoding("UTF-8");
        templateResolver.setCacheable(true);
        SpringTemplateEngine engine = new SpringTemplateEngine();
        engine.setTemplateResolver(templateResolver);
        engine.setEnableSpringELCompiler(true);
        ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
        viewResolver.setTemplateEngine(engine);
        viewResolver.setCharacterEncoding("UTF-8");
        System.out.println("ThymeleafViewResolver OK");
        return viewResolver;
    }
}
